﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class playermanager : MonoBehaviour
{
    private float h, v;
    public float speed;
    public GameObject bullet;
    public GameObject explosion;
    public GameObject born;
    public AudioClip Ac;
    private SpriteRenderer sr;
    public Sprite[] tanks;
    public float cooldown;
    private float cdtiming;
    private int flag;

    private void Awake()
    {
        sr = GetComponent<SpriteRenderer>();
    }
    void Start ()
    {
        cdtiming = 0;
	}
    private void FixedUpdate()
    {
        move();
    }

    void Update ()
    {
        
        if (cdtiming>0)cdtiming -= Time.deltaTime;
        change();
        attack();
        //debug();
	}

    private void move()
    {
        v = Input.GetAxisRaw("Vertical");
        h = Input.GetAxisRaw("Horizontal");
        transform.Translate(new Vector3(0, speed * Time.fixedDeltaTime * v, 0));
        if (v > 0.5f) flag = 0;
        if (v < -0.5f) flag = 2;
        if (Mathf.Abs(v) > 0.5) return;
        transform.Translate(new Vector3(speed * Time.fixedDeltaTime * h, 0, 0));
        if (h > 0.5f) flag = 1;
        if (h < -0.5f) flag = 3;
    }
    private void attack()
    {
        if (cdtiming > 0) return;
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Instantiate(bullet, transform.position, Quaternion.Euler(0,0,-90*flag));
            cdtiming = cooldown;
            AudioSource.PlayClipAtPoint(Ac, transform.position);
        }
    }
    private void change()
    {
        sr.sprite = tanks[flag];
    }
    public void damaged()
    {
        if (GameObject.Find("protection") != null) return;
        Instantiate(explosion, transform.position, Quaternion.Euler(0, 0, 0));
        Instantiate(born, new Vector3(-2, -8, 0), Quaternion.identity);
        Destroy(gameObject);
    }
    public void debug()
    {
        if (Input.GetKeyDown(KeyCode.Q)) damaged();
    }
}
